package org.fast.develop.logicflow.runtime.convert.execute;

import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.fast.develop.logicflow.core.meta.exception.LogicFlowMetaException;
import org.fast.develop.logicflow.runtime.convert.builder.DesignerModelBuilder;
import org.fast.develop.logicflow.runtime.convert.builder.impl.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author czh
 * @version V1.0
 * @data Created on 2022-12-31 11:31
 */
@Slf4j
public class DesignerBuilderFactory {

    Map<String, Class<? extends DesignerModelBuilder>> builderClasses = new HashMap<>();

    @SneakyThrows
    public DesignerBuilderFactory() {
        builderClasses.put(DesignerStartModelBuilder.class.newInstance().getType(), DesignerStartModelBuilder.class);
        builderClasses.put(DesignerSequenceModelBuilder.class.newInstance().getType(), DesignerSequenceModelBuilder.class);
        builderClasses.put(DesignerJavaClassTaskModelBuilder.class.newInstance().getType(), DesignerJavaClassTaskModelBuilder.class);
        builderClasses.put(DesignerElseIfControlModelBuilder.class.newInstance().getType(), DesignerElseIfControlModelBuilder.class);
        builderClasses.put(DesignerEndModelBuilder.class.newInstance().getType(), DesignerEndModelBuilder.class);
    }

    public void register(String name, Class<? extends DesignerModelBuilder> builderClass){
        if(builderClasses.get(name) != null){
            throw new LogicFlowMetaException(StrUtil.format("{}:注册名已存在，不要重复注册", name));
        }
        builderClasses.put(name, builderClass);
    }

    public DesignerModelBuilder create(String name){
        try {
            Class<? extends DesignerModelBuilder> builderClass = builderClasses.get(name);
            if(Objects.nonNull(builderClass)){
                return builderClass.newInstance();
            } else {
                throw new LogicFlowMetaException(StrUtil.format("{}:类型不存在，获取构造器失败", name));
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
